﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Practices.Unity.WebApi;

using ERPStore.Extensions;

[assembly: System.Web.PreApplicationStartMethod(typeof(ERPStore.Web.Start.UnityWebApiActivator), "Start")]

namespace ERPStore.Web.Start
{
	public static class UnityWebApiActivator
	{
		/// <summary>Integrates Unity when the application starts.</summary>
		public static void Start()
		{
			var container = GlobalConfiguration.Configuration.DependencyResolver.GetContainer();
			// Use UnityHierarchicalDependencyResolver if you want to use a new child container for each IHttpController resolution.
			// var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer());
			var resolver = new UnityDependencyResolver(container);

			System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = resolver;

			// System.Web.Http.GlobalConfiguration.Configuration.MessageHandlers.Add(new Logging.WebApiLoggerHandler());
			if (GlobalConfiguration.Configuration.DebugEnabled)
			{
				System.Web.Http.GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = System.Web.Http.IncludeErrorDetailPolicy.Always;
			}
			System.Web.Http.GlobalConfiguration.Configuration.Filters.Add(new Controllers.ActionFilters.LogExceptionFilter());
			System.Web.Http.GlobalConfiguration.Configuration.Filters.Add(new Controllers.ActionFilters.ValidationFilterAttribute());
			// System.Web.Http.GlobalConfiguration.Configuration.Services.Replace(typeof(System.Web.Http.Tracing.ITraceWriter), new Logging.WebApiTraceWriter(logger));
			var userPrincipaHandler = new Services.UserPrincipalHandler();
			System.Web.Http.GlobalConfiguration.Configuration.MessageHandlers.Add(userPrincipaHandler);

			var appXmlType = System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
			System.Web.Http.GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

		}
	}
}
